local id_list = {}
local quantity_list = {}
local keys = KEYS
local values = ARGV

local function deduction(key, num)
    keys[1] = key
    local value = redis.call("get", keys[1])
    if not value then
        value = 0
    end
    value = value + num
    if (value < 0)
    then
        return false
    end
        redis.call("set", keys[1], value)
    return true
end

local function rollback ()
    for i, k in ipairs (id_list)
    do
        keys[1] = k
        redis.call("incrby", keys[1], 0-quantity_list[1])
    end
end

local function execute ()
    for i, k in ipairs (values)
    do
        local num = tonumber(k)
        local key = keys[i]

        local result = deduction(key, num)

        if (result == false)
        then
            rollback()
            return false
        else
            table.insert(id_list, key)
            table.insert(quantity_list, num)
        end
    end
    return true
end

return execute()